class TrustBranchManager {
  constructor() {
    this.storyTemplates = {
      // 基础信任建立剧情
      'trust-building': {
        id: 'trust-building',
        title: '信任的建立',
        subtitle: '在合作中建立信任关系',
        steps: [
          {
            id: 'step1',
            title: '初次相遇',
            content: '你遇到了一个陌生人，他需要你的帮助。你会选择帮助他吗？',
            character: {
              name: '陌生人',
              icon: '👤',
              description: '一个看起来需要帮助的人'
            },
            branches: [
              {
                id: 'help',
                title: '主动帮助',
                icon: '🤝',
                description: '毫不犹豫地伸出援手',
                trustImpact: 15,
                resultTitle: '建立信任',
                resultContent: '你的善意得到了回应，对方开始信任你。',
                specialEffects: [
                  {
                    id: 'trust_bonus',
                    icon: '✨',
                    description: '获得信任加成：下次合作时信任值+5'
                  }
                ]
              },
              {
                id: 'hesitate',
                title: '犹豫不决',
                icon: '🤔',
                description: '先观察一下情况',
                trustImpact: 5,
                resultTitle: '谨慎接触',
                resultContent: '你的谨慎让对方感到安全，建立了初步信任。'
              },
              {
                id: 'ignore',
                title: '置之不理',
                icon: '😐',
                description: '选择不介入',
                trustImpact: -10,
                resultTitle: '错失机会',
                resultContent: '你错过了建立信任的机会。'
              }
            ]
          },
          {
            id: 'step2',
            title: '信任考验',
            content: '对方邀请你参与一个需要相互信任的项目。这个项目有风险，但成功后收益很大。',
            branches: [
              {
                id: 'accept',
                title: '接受邀请',
                icon: '✅',
                description: '相信对方，参与项目',
                trustImpact: 20,
                requirements: [
                  {
                    type: 'trustValue',
                    value: 30,
                    description: '需要基础信任值'
                  }
                ],
                resultTitle: '深度合作',
                resultContent: '你们建立了深度的信任关系，项目进展顺利。'
              },
              {
                id: 'negotiate',
                title: '协商条件',
                icon: '🤝',
                description: '提出保护措施后再参与',
                trustImpact: 10,
                resultTitle: '理性合作',
                resultContent: '你们达成了平衡的合作协议。'
              },
              {
                id: 'decline',
                title: '拒绝邀请',
                icon: '❌',
                description: '认为风险太大',
                trustImpact: -5,
                resultTitle: '保持距离',
                resultContent: '你选择了保守，但可能错过了机会。'
              }
            ]
          }
        ]
      },
      
      // 信任危机剧情
      'trust-crisis': {
        id: 'trust-crisis',
        title: '信任的考验',
        subtitle: '面对背叛时的选择',
        steps: [
          {
            id: 'step1',
            title: '发现背叛',
            content: '你发现合作伙伴在背后做了损害你利益的事情。你会如何处理？',
            character: {
              name: '合作伙伴',
              icon: '🤝',
              description: '曾经信任的合作伙伴'
            },
            branches: [
              {
                id: 'confront',
                title: '直接质问',
                icon: '😠',
                description: '当面质问对方的行为',
                trustImpact: -15,
                resultTitle: '关系破裂',
                resultContent: '直接的对质导致关系彻底破裂。'
              },
              {
                id: 'investigate',
                title: '调查真相',
                icon: '🔍',
                description: '先调查清楚再决定',
                trustImpact: 0,
                resultTitle: '理性处理',
                resultContent: '你选择了理性的方式处理问题。'
              },
              {
                id: 'forgive',
                title: '选择原谅',
                icon: '💝',
                description: '给对方一次机会',
                trustImpact: 10,
                requirements: [
                  {
                    type: 'trustValue',
                    value: 60,
                    description: '需要高信任值才能选择原谅'
                  }
                ],
                resultTitle: '重建信任',
                resultContent: '你的宽容让对方深受感动，关系得到修复。'
              }
            ]
          }
        ]
      },
      
      // 信任传承剧情
      'trust-legacy': {
        id: 'trust-legacy',
        title: '信任的传承',
        subtitle: '将信任传递给下一代',
        steps: [
          {
            id: 'step1',
            title: '传承时刻',
            content: '你即将离开，需要将重要的信任关系传承给其他人。',
            character: {
              name: '继承人',
              icon: '👨‍💼',
              description: '你选择的信任继承人'
            },
            branches: [
              {
                id: 'full_trust',
                title: '完全信任',
                icon: '💯',
                description: '将所有的信任关系都传承给对方',
                trustImpact: 25,
                requirements: [
                  {
                    type: 'trustValue',
                    value: 80,
                    description: '需要极高的信任值'
                  }
                ],
                resultTitle: '完美传承',
                resultContent: '你的信任得到了完美的传承，关系网络得以延续。'
              },
              {
                id: 'gradual_handover',
                title: '逐步交接',
                icon: '📈',
                description: '分阶段地传承信任关系',
                trustImpact: 15,
                resultTitle: '平稳过渡',
                resultContent: '信任关系得到了平稳的传承。'
              },
              {
                id: 'conditional_trust',
                title: '有条件信任',
                icon: '⚠️',
                description: '设置条件后再传承',
                trustImpact: 5,
                resultTitle: '谨慎传承',
                resultContent: '你选择了谨慎的传承方式。'
              }
            ]
          }
        ]
      }
    }
    
    this.currentStory = null
    this.storyHistory = []
  }
  
  // 获取剧情模板
  getStoryTemplate(storyId) {
    return this.storyTemplates[storyId] || null
  }
  
  // 获取所有剧情模板
  getAllStoryTemplates() {
    return Object.values(this.storyTemplates)
  }
  
  // 开始新剧情
  startStory(storyId, initialTrustValue = 50) {
    const template = this.getStoryTemplate(storyId)
    if (!template) {
      console.error(`Story template not found: ${storyId}`)
      return null
    }
    
    this.currentStory = {
      ...template,
      currentStep: 1,
      trustValue: initialTrustValue,
      startTime: Date.now(),
      choices: []
    }
    
    this.storyHistory.push({
      storyId: storyId,
      startTime: this.currentStory.startTime,
      initialTrustValue: initialTrustValue
    })
    
    return this.currentStory
  }
  
  // 记录选择
  recordChoice(stepId, branchId, trustChange) {
    if (!this.currentStory) return false
    
    const choice = {
      stepId: stepId,
      branchId: branchId,
      trustChange: trustChange,
      timestamp: Date.now()
    }
    
    this.currentStory.choices.push(choice)
    this.currentStory.trustValue = Math.max(0, Math.min(100, this.currentStory.trustValue + trustChange))
    
    return true
  }
  
  // 获取当前剧情
  getCurrentStory() {
    return this.currentStory
  }
  
  // 完成剧情
  completeStory() {
    if (!this.currentStory) return null
    
    const result = {
      storyId: this.currentStory.id,
      finalTrustValue: this.currentStory.trustValue,
      totalChoices: this.currentStory.choices.length,
      duration: Date.now() - this.currentStory.startTime,
      choices: this.currentStory.choices
    }
    
    // 保存到历史记录
    this.storyHistory[this.storyHistory.length - 1].result = result
    
    this.currentStory = null
    return result
  }
  
  // 获取剧情历史
  getStoryHistory() {
    return this.storyHistory
  }
  
  // 获取信任统计
  getTrustStatistics() {
    const stats = {
      totalStories: this.storyHistory.length,
      averageTrustValue: 0,
      trustDistribution: {
        high: 0,    // >= 80
        medium: 0,  // 50-79
        low: 0,     // 20-49
        broken: 0   // < 20
      },
      mostCommonChoices: {},
      trustTrend: []
    }
    
    if (this.storyHistory.length === 0) return stats
    
    let totalTrust = 0
    this.storyHistory.forEach(entry => {
      if (entry.result) {
        totalTrust += entry.result.finalTrustValue
        
        // 信任分布
        const trustValue = entry.result.finalTrustValue
        if (trustValue >= 80) stats.trustDistribution.high++
        else if (trustValue >= 50) stats.trustDistribution.medium++
        else if (trustValue >= 20) stats.trustDistribution.low++
        else stats.trustDistribution.broken++
        
        // 信任趋势
        stats.trustTrend.push({
          storyId: entry.storyId,
          trustValue: trustValue,
          timestamp: entry.startTime
        })
        
        // 最常见选择
        entry.result.choices.forEach(choice => {
          const key = `${choice.stepId}-${choice.branchId}`
          stats.mostCommonChoices[key] = (stats.mostCommonChoices[key] || 0) + 1
        })
      }
    })
    
    stats.averageTrustValue = totalTrust / this.storyHistory.length
    
    return stats
  }
  
  // 生成剧情推荐
  generateStoryRecommendations(currentTrustValue) {
    const recommendations = []
    
    // 基于信任值推荐剧情
    if (currentTrustValue < 30) {
      recommendations.push({
        storyId: 'trust-building',
        reason: '你的信任值较低，建议从基础信任建立开始',
        priority: 'high'
      })
    } else if (currentTrustValue >= 30 && currentTrustValue < 70) {
      recommendations.push({
        storyId: 'trust-crisis',
        reason: '你的信任值中等，可以尝试信任考验剧情',
        priority: 'medium'
      })
    } else if (currentTrustValue >= 70) {
      recommendations.push({
        storyId: 'trust-legacy',
        reason: '你的信任值很高，可以尝试信任传承剧情',
        priority: 'high'
      })
    }
    
    // 基于历史记录推荐
    const stats = this.getTrustStatistics()
    if (stats.trustDistribution.broken > stats.trustDistribution.high) {
      recommendations.push({
        storyId: 'trust-building',
        reason: '你最近信任关系破裂较多，建议重新建立信任',
        priority: 'high'
      })
    }
    
    return recommendations
  }
  
  // 保存剧情数据到本地存储
  saveStoryData() {
    try {
      const data = {
        storyHistory: this.storyHistory,
        lastUpdate: Date.now()
      }
      uni.setStorageSync('trustBranchData', JSON.stringify(data))
      return true
    } catch (error) {
      console.error('Failed to save story data:', error)
      return false
    }
  }
  
  // 从本地存储加载剧情数据
  loadStoryData() {
    try {
      const data = uni.getStorageSync('trustBranchData')
      if (data) {
        const parsedData = JSON.parse(data)
        this.storyHistory = parsedData.storyHistory || []
        return true
      }
    } catch (error) {
      console.error('Failed to load story data:', error)
    }
    return false
  }
  
  // 清除所有剧情数据
  clearStoryData() {
    this.storyHistory = []
    this.currentStory = null
    try {
      uni.removeStorageSync('trustBranchData')
      return true
    } catch (error) {
      console.error('Failed to clear story data:', error)
      return false
    }
  }
}

export default new TrustBranchManager()

